/*
 Xern Entity Relocation Network
 Copyright (C) 2010-2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include "Xern/IRenderer.hpp"
#include "Xern/IPhysicRegion.hpp"
#include "Xern/IMovableObject.hpp"
#include "Xern/IMovementListener.hpp"

#include "Xern/Entity.hpp"
#include "Xern/Engine.hpp"
#include "Xern/Region.hpp"
#include "Xern/ResourceManager.hpp"
#include "Xern/WorldManager.hpp"

namespace Xern
{
	Entity::Entity()
		: linearVelocity(0.0f),
		  linearAcceleration(0.0f),
		  angularVelocity(0.0f),
		  hasPhysicAction(false)
	{
		CreateSceneNode();
		creationTime = posix_time::microsec_clock::universal_time();
		lastMovementTime = creationTime;
		lastPhysicChangeTime = creationTime;
		guid = nil_uuid();
	}

	Entity::~Entity()
	{
		Clear();
	}

	void Entity::Clear()
	{
		Children::iterator it = children.begin();
		for(; it != children.end(); it++)
		{
			boost::shared_ptr<Entity> child = *it;
			child->Clear();
		}

		// Destroy the rigid body.
		if(rigidBody)
		{
			boost::shared_ptr<Region> region = GetRegion();
			if(region)
			{
				boost::shared_ptr<IPhysicRegion> physicRegion = region->GetPhysicRegion();
				physicRegion->RemoveRigidBody(rigidBody);
				if(hasPhysicAction)
					physicRegion->RemoveAction(rigidBody);
			}
			rigidBody.reset();
		}

		sceneNode.reset();
		children.clear();
		resources.clear();
		objects.clear();
		movementListeners.clear();
	}

	boost::shared_ptr<Region> Entity::GetRegion()
	{
		boost::shared_ptr<Entity> p = parent.lock();
		if(p)
			return p->GetRegion();
		return boost::shared_ptr<Region> ();
	}

	boost::shared_ptr<const Region> Entity::GetRegion() const
	{
		boost::shared_ptr<Entity> p = parent.lock();
		if(p)
			return p->GetRegion();
		return boost::shared_ptr<Region> ();
	}

	const uuid &Entity::GetId() const
	{
		return guid;
	}

	void Entity::SetId(const uuid &id)
	{
		Engine::Get().GetWorldManager()->UpdateEntityID(shared_from_this(), guid, id);
		guid = id;
	}

	const std::string &Entity::GetName() const
	{
		return name;
	}

	void Entity::SetName(const std::string &name)
	{
		this->name = name;
	}

	const std::string &Entity::GetClassName() const
	{
		return className;
	}

	void Entity::SetClassName(const std::string &className)
	{
		this->className = className;
	}

	void Entity::SetTransform(const ReversibleTransform &transform)
	{
		this->transform = transform;

		// Update the scene node.
		if(sceneNode)
			sceneNode->SetTransform(transform);

		// Notify movement change.
		NotifyMovement();
	}

	const ReversibleTransform &Entity::GetTransform() const
	{
		return transform;
	}

	ReversibleTransform Entity::GetWorldTransform() const
	{
		boost::shared_ptr<const Entity> parent = GetParent();
		if(parent)
			return parent->GetWorldTransform() * transform;
		return transform;
	}

	void Entity::SetLinearVelocity(const Vector3 &velocity)
	{
		linearVelocity = velocity;

		// Notify movement change.
		NotifyMovement();
	}

	const Vector3 &Entity::GetLinearVelocity() const
	{
		return linearVelocity;
	}

	// Linear acceleration.
	void Entity::SetLinearAcceleration(const Vector3 &acceleration)
	{
		linearAcceleration = acceleration;

		// Notify movement change.
		NotifyMovement();
	}

	const Vector3 &Entity::GetLinearAcceleration() const
	{
		return linearAcceleration;
	}

	void Entity::SetAngularVelocity(const Vector3 &velocity)
	{
		angularVelocity = velocity;

		// Notify movement change.
		NotifyMovement();
	}

	const Vector3 &Entity::GetAngularVelocity() const
	{
		return angularVelocity;
	}

	void Entity::AddMovementListener(boost::shared_ptr<IMovementListener> listener)
	{
		movementListeners.insert(listener);
	}

	void Entity::RemoveMovementListener(boost::shared_ptr<IMovementListener> listener)
	{
		movementListeners.erase(listener);
	}

	boost::shared_ptr<ISceneNode> Entity::GetSceneNode()
	{
		return sceneNode;
	}

	boost::shared_ptr<const ISceneNode> Entity::GetSceneNode() const
	{
		return sceneNode;
	}

	void Entity::NotifyMovement(bool parent)
	{
		// Update the last movement time.
		if(!parent)
			lastMovementTime = GetCurrentTime();

		// Notify the listeners.
		boost::shared_ptr<Entity> self = shared_from_this();
		MovementListeners::const_iterator it = movementListeners.begin();
		for(; it != movementListeners.end(); it++)
		{
			boost::shared_ptr<IMovementListener> listener = *it;
			listener->OnMove(self);
		}

		// Notify the children.
		Children::iterator cit = children.begin();
		for(; cit != children.end(); cit++)
		{
			boost::shared_ptr<Entity> child = *cit;
			child->NotifyMovement(true);
		}
	}

	void Entity::SetRigidBody(boost::shared_ptr<IRigidBody> body)
	{
		// Don't perform needless updates.
		if(rigidBody == body)
			return;

		// Update the last physic change time.
		lastPhysicChangeTime = GetCurrentTime();

		// Update the physic region.
		boost::shared_ptr<Region> region = GetRegion();
		boost::shared_ptr<IPhysicRegion> physicRegion;
		if(region)
			physicRegion = region->GetPhysicRegion();

		if(rigidBody && physicRegion)
		{
			physicRegion->RemoveRigidBody(rigidBody);
			if(hasPhysicAction)
				physicRegion->RemoveAction(rigidBody);
		}

		rigidBody = body;

		if(rigidBody && region)
		{
			physicRegion->AddRigidBody(rigidBody);
			if(hasPhysicAction)
				physicRegion->AddAction(rigidBody);
		}
	}

	boost::shared_ptr<IRigidBody> Entity::GetRigidBody()
	{
		return rigidBody;
	}

	boost::shared_ptr<const IRigidBody> Entity::GetRigidBody() const
	{
		return rigidBody;
	}

	boost::shared_ptr<Entity> Entity::GetParent()
	{
		return parent.lock();
	}

	boost::shared_ptr<const Entity> Entity::GetParent() const
	{
		return parent.lock();
	}

	int Entity::GetChildCount() const
	{
		return children.size();
	}

	void Entity::AddChild(boost::shared_ptr<Entity> child)
	{
		if(!child || child->parent.lock() == shared_from_this())
			return;

		// Store the regions.
		boost::shared_ptr<Region> oldRegion = child->GetRegion();
		boost::shared_ptr<Region> newRegion = GetRegion();

		// Remove from the old parent.
		boost::shared_ptr<Entity> oldParent = child->parent.lock();
		boost::shared_ptr<ISceneNode> pnode;
		if(oldParent)
		{
			pnode = oldParent->sceneNode;
			oldParent->children.erase(child);
		}

		// Update the child parent.
		child->parent = shared_from_this();
		children.insert(child);

		// Notify the regions.
		if(oldRegion != newRegion && newRegion != child)
		{
			if(oldRegion)
				oldRegion->OnRemoveEntity(child);

			if(newRegion)
				newRegion->OnAddEntity(child);
		}

		// Update the scene node.
		boost::shared_ptr<ISceneNode> cnode = child->sceneNode;
		if(cnode && pnode)
			pnode->RemoveChild(cnode);
		if(cnode && sceneNode)
			sceneNode->AddChild(cnode);

		// Notify the child.
		child->NotifyMovement();
	}

	void Entity::RemoveChild(boost::shared_ptr<Entity> child)
	{
		if(!child)
			return;

		// Store the regions.
		boost::shared_ptr<Region> oldRegion = GetRegion();

		child->parent.reset();
		children.erase(child);

		// Notify the region.
		if(oldRegion)
			oldRegion->OnRemoveEntity(child);

		// Update the scene node.
		boost::shared_ptr<ISceneNode> cnode = child->sceneNode;
		if(cnode && sceneNode)
			sceneNode->RemoveChild(cnode);

		// Notify the child.
		child->NotifyMovement();
	}

	const Entity::Children &Entity::GetChildren()
	{
		return children;
	}

	boost::shared_ptr<Entity> Entity::FindChildByName(const std::string &name)
	{
		boost::shared_ptr<Entity> ret;
		Children::const_iterator it = children.begin();
		for(; it != children.end(); it++)
		{
			boost::shared_ptr<Entity> child = *it;
			if(child->GetName() == name)
				return child;
			ret = child->FindChildByName(name);
			if(ret)
				return ret;
		}
		return ret;
	}

	boost::shared_ptr<Entity> Entity::FindChildByClassName(const std::string &classname)
	{
		boost::shared_ptr<Entity> ret;
		Children::const_iterator it = children.begin();
		for(; it != children.end(); it++)
		{
			boost::shared_ptr<Entity> child = *it;
			if(child->GetClassName() == classname)
				return child;
			ret = child->FindChildByClassName(classname);
			if(ret)
				return ret;
		}
		return ret;
	}

	boost::shared_ptr<Entity> Entity::FindChildById(const uuid &id)
	{
		boost::shared_ptr<Entity> ret;
		Children::const_iterator it = children.begin();
		for(; it != children.end(); it++)
		{
			boost::shared_ptr<Entity> child = *it;
			if(child->GetId() == id)
				return child;
			ret = child->FindChildById(id);
			if(ret)
				return ret;
		}
		return ret;
	}

	int Entity::GetResourceCount() const
	{
		return resources.size();
	}

	void Entity::AddResource(boost::shared_ptr<IResource> resource)
	{
		if(!resource)
			return;

		resources.insert(resource);

		// Check the resource flags for additional supported interfaces.
		IResource::ResourceFlags flags = resource->GetFlags();

		if(flags & IResource::RFL_MOVABLE_OBJECT)
		{
			boost::shared_ptr<IMovableObject> object =
					boost::dynamic_pointer_cast<IMovableObject> (resource);
			if(object)
				AddObject(object);
		}

		if(flags & IResource::RFL_MOVEMENT_LISTENER)
		{
			boost::shared_ptr<IMovementListener> listener =
					boost::dynamic_pointer_cast<IMovementListener> (resource);
			if(listener)
			{
				AddMovementListener(listener);
				// Send initial move.
				listener->OnMove(shared_from_this());
			}
		}

		// Notify the resource manager.
		Engine::Get().GetResourceManager()->OnAddedResource(shared_from_this(), resource);
	}

	void Entity::RemoveResource(boost::shared_ptr<IResource> resource)
	{
		if(!resource)
			return;

		resources.erase(resource);

		// Check the resource flags for additional supported interfaces.
		IResource::ResourceFlags flags = resource->GetFlags();

		if(flags & IResource::RFL_MOVABLE_OBJECT)
		{
			boost::shared_ptr<IMovableObject> object =
					boost::dynamic_pointer_cast<IMovableObject> (resource);
			if(object)
				RemoveObject(object);
		}

		if(flags & IResource::RFL_MOVEMENT_LISTENER)
		{
			boost::shared_ptr<IMovementListener> listener =
					boost::dynamic_pointer_cast<IMovementListener> (resource);
			if(listener)
				RemoveMovementListener(listener);
		}

		// Notify the resource manager.
		Engine::Get().GetResourceManager()->OnRemovedResource(shared_from_this(), resource);
	}

	const Entity::Resources &Entity::GetResources() const
	{
		return resources;
	}

	void Entity::AddObject(boost::shared_ptr<IMovableObject> object)
	{
		if(!object)
			return;

		// Attach to the scene node.
		if(sceneNode)
			sceneNode->AttachObject(object);
	}

	void Entity::RemoveObject(boost::shared_ptr<IMovableObject> object)
	{
		if(!object)
			return;

		// Dettach from the scene node.
		if(sceneNode)
			sceneNode->DetachObject(object);
	}

	bool Entity::ParseProperty(const std::string &key, const std::string &value)
	{
		return false;
	}

	bool Entity::Frame(float delta)
	{
		return true;
	}

	void Entity::PhysicAction(float delta)
	{
	}

	void Entity::Spawn()
	{
	}

	void Entity::OnTouch(boost::shared_ptr<Entity> other)
	{
	}

	void Entity::OnEvent(const std::string &name, const std::string &sender, const std::string &data)
	{
	}

	void Entity::CreateSceneNode()
	{
		boost::shared_ptr<IRenderer> renderer = Engine::Get().GetRenderer();
		if(renderer)
			SetSceneNode(renderer->CreateSceneNode());
	}

	void Entity::SetSceneNode(boost::shared_ptr<ISceneNode> sceneNode)
	{
		this->sceneNode = sceneNode;
	}

	bool Entity::HasPhysicAction() const
	{
		return hasPhysicAction;
	}

	void Entity::EnablePhysicAction()
	{
		hasPhysicAction = true;

		if(!rigidBody)
			return;

		boost::shared_ptr<Region> region = GetRegion();
		if(region)
			region->GetPhysicRegion()->AddAction(rigidBody);
	}

	void Entity::DisablePhysicAction()
	{
		hasPhysicAction = false;

		if(!rigidBody)
			return;

		boost::shared_ptr<Region> region = GetRegion();
		if(region)
			region->GetPhysicRegion()->RemoveAction(rigidBody);
	}

	const posix_time::ptime &Entity::GetCreationTime() const
	{
		return creationTime;
	}

	const posix_time::ptime &Entity::GetLastMovementTime() const
	{
		return lastMovementTime;
	}

	const posix_time::ptime &Entity::GetLastPhysicChangeTime() const
	{
		return lastPhysicChangeTime;
	}

}; // namespace Xern
